using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PowerUpManager : MonoBehaviour
{
    // 单例模式
    public static PowerUpManager Instance { get; private set; }
    
    [Header("当前激活的道具效果")]
    public List<ActivePowerUp> activePowerUps = new List<ActivePowerUp>();
    
    [Header("道具效果设置")]
    public float maxEffectStack = 3f; // 同类效果最大叠加数
    public bool allowStacking = true; // 是否允许效果叠加
    
    
    [Header("调试设置")]
    public bool showDebugInfo = true;
    
    // 组件引用
    private BulletSpawner bulletSpawner;
    private PlayerController playerController;
    
    // 原始属性备份
    private float originalFireRate;
    private BulletSpawner.ShootingMode originalShootingMode;
    private float originalBulletSpeed;
    private int originalBulletDamage;
    
    [System.Serializable]
    public class ActivePowerUp
    {
        public PowerUpController.PowerUpType type;
        public float remainingTime;
        public float effectStrength;
        public bool isActive;
        public List<GameObject> spawnedObjects; // 用于Clone等需要生成实体的效果
        
        public ActivePowerUp(PowerUpController.PowerUpType type, float duration, float strength)
        {
            this.type = type;
            this.remainingTime = duration;
            this.effectStrength = strength;
            this.isActive = true;
            this.spawnedObjects = null;
        }
    }
    
    void Awake()
    {
        // 单例模式初始化
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }
    
    void Start()
    {
        
        // 获取组件引用
        bulletSpawner = GetComponent<BulletSpawner>();
        playerController = GetComponent<PlayerController>();
        
        // 若当前对象上没有 BulletSpawner/PlayerController，则尝试从 Player 标签对象上获取（含子节点）
        if (bulletSpawner == null || playerController == null)
        {
            GameObject player = GameObject.FindGameObjectWithTag("Player");
            
            if (player != null)
            {
                if (bulletSpawner == null)
                {
                    bulletSpawner = player.GetComponentInChildren<BulletSpawner>();
                }
                if (playerController == null)
                {
                    playerController = player.GetComponent<PlayerController>();
                }
            }
        }
        
        // 如果还是找不到，尝试全局查找
        if (bulletSpawner == null)
        {
            bulletSpawner = FindObjectOfType<BulletSpawner>();
        }
        
        // 备份原始属性（确保在最终引用就绪后）
        if (bulletSpawner != null)
        {
            originalFireRate = bulletSpawner.fireRate;
            originalShootingMode = bulletSpawner.shootingMode;
            originalBulletSpeed = bulletSpawner.bulletSpeed;
            originalBulletDamage = bulletSpawner.bulletDamage;
        }
        
    }
    
    void InitializeBulletSpawner()
    {
        // 获取组件引用
        bulletSpawner = GetComponent<BulletSpawner>();
        playerController = GetComponent<PlayerController>();
        
        
        // 若当前对象上没有 BulletSpawner/PlayerController，则尝试从 Player 标签对象上获取（含子节点）
        if (bulletSpawner == null || playerController == null)
        {
            GameObject player = GameObject.FindGameObjectWithTag("Player");
            
            if (player != null)
            {
                if (bulletSpawner == null)
                {
                    bulletSpawner = player.GetComponentInChildren<BulletSpawner>();
                }
                if (playerController == null)
                {
                    playerController = player.GetComponent<PlayerController>();
                }
            }
        }
        
        // 如果还是找不到，尝试全局查找
        if (bulletSpawner == null)
        {
            bulletSpawner = FindObjectOfType<BulletSpawner>();
        }
        
        // 备份原始属性（确保在最终引用就绪后）
        if (bulletSpawner != null)
        {
            originalFireRate = bulletSpawner.fireRate;
            originalShootingMode = bulletSpawner.shootingMode;
            originalBulletSpeed = bulletSpawner.bulletSpeed;
            originalBulletDamage = bulletSpawner.bulletDamage;
        }
    }
    
    void Update()
    {
        UpdateActivePowerUps();
        HandleSpecialSkills();
        
        if (showDebugInfo && activePowerUps.Count > 0)
        {
            Debug.Log($"激活道具数量: {activePowerUps.Count}");
        }
    }
    
    void UpdateActivePowerUps()
    {
        for (int i = activePowerUps.Count - 1; i >= 0; i--)
        {
            ActivePowerUp powerUp = activePowerUps[i];
            powerUp.remainingTime -= Time.deltaTime;
            
            if (powerUp.remainingTime <= 0)
            {
                RemovePowerUpEffect(powerUp);
                activePowerUps.RemoveAt(i);
            }
        }
        
    }
    
    void HandleSpecialSkills()
    {
        // 简化版本暂时不需要特殊技能
    }
    
    public void ApplyPowerUp(PowerUpController.PowerUpType type, float duration, float strength)
    {
        switch (type)
        {
            case PowerUpController.PowerUpType.SpreadShot:
                ApplySpreadShot(duration, strength);
                break;
            case PowerUpController.PowerUpType.BurstFire:
                ApplyBurstFire(duration, strength);
                break;
            case PowerUpController.PowerUpType.UpgradedBullet:
                ApplyBulletUpgrade(duration, strength);
                break;
            case PowerUpController.PowerUpType.BulletUpgradePowerUp:
                ApplyBulletUpgradePowerUp(duration, strength);
                break;
            case PowerUpController.PowerUpType.Clone:
                ApplyClone(duration, strength);
                break;
        }
        
        Debug.Log($"应用道具效果: {type}, 持续时间: {duration}s, 强度: {strength}");
    }
    
    
    void ApplySpreadShot(float duration, float strength)
    {
        // 如果 bulletSpawner 为 null，尝试重新初始化
        if (bulletSpawner == null) 
        {
            Debug.LogWarning("[PowerUpManager] bulletSpawner为null，尝试重新查找...");
            InitializeBulletSpawner();
            
            if (bulletSpawner == null)
            {
                Debug.LogError("[PowerUpManager] 重新查找后仍然为null，无法应用SpreadShot效果");
                return;
            }
        }

        Debug.Log($"[PowerUpManager] 应用SpreadShot效果: 持续时间={duration}s, 强度={strength}");
        
        ActivePowerUp existing = FindActivePowerUp(PowerUpController.PowerUpType.SpreadShot);
        
        if (existing != null)
        {
            existing.remainingTime = duration;
            Debug.Log("[PowerUpManager] 刷新现有SpreadShot效果时间");
        }
        else
        {
            activePowerUps.Add(new ActivePowerUp(PowerUpController.PowerUpType.SpreadShot, duration, strength));
            Debug.Log("[PowerUpManager] 添加新的SpreadShot效果，调用SetShootingMode");
            bulletSpawner.SetShootingMode(BulletSpawner.ShootingMode.Spread);
        }
    }
    
    void ApplyBurstFire(float duration, float strength)
    {
        if (bulletSpawner == null) return;
        
        ActivePowerUp existing = FindActivePowerUp(PowerUpController.PowerUpType.BurstFire);
        
        if (existing != null)
        {
            existing.remainingTime = duration;
        }
        else
        {
            activePowerUps.Add(new ActivePowerUp(PowerUpController.PowerUpType.BurstFire, duration, strength));
            bulletSpawner.SetShootingMode(BulletSpawner.ShootingMode.Burst);
        }
    }

    void ApplyBulletUpgrade(float duration, float strength)
    {
        // strength 在此版本用于预留，暂未作为等级加成倍数，未来可用作一次升多级
        if (bulletSpawner == null)
        {
            Debug.LogWarning("[PowerUpManager] bulletSpawner为null，尝试重新查找...");
            InitializeBulletSpawner();
            if (bulletSpawner == null)
            {
                Debug.LogError("[PowerUpManager] 重新查找后仍然为null，无法应用BulletUpgrade效果");
                return;
            }
        }

        // 升级一次
        bulletSpawner.UpgradeBullet();

        // 记录一个可到期的升级效果
        activePowerUps.Add(new ActivePowerUp(PowerUpController.PowerUpType.UpgradedBullet, duration, strength));
        Debug.Log($"[PowerUpManager] 应用BulletUpgrade: 持续时间={duration}s");
    }

    void ApplyClone(float duration, float strength)
    {
        if (bulletSpawner == null)
        {
            InitializeBulletSpawner();
            if (bulletSpawner == null)
            {
                Debug.LogError("[PowerUpManager] 未找到BulletSpawner，无法应用Clone效果");
                return;
            }
        }

        int count = Mathf.Max(1, Mathf.RoundToInt(strength));
        var ap = new ActivePowerUp(PowerUpController.PowerUpType.Clone, duration, strength);
        ap.spawnedObjects = new List<GameObject>();

        // 均匀环绕：以玩家为父对象，设置局部偏移
        Transform parent = playerController != null ? playerController.transform : transform;
        float radius = 0.8f;
        for (int i = 0; i < count; i++)
        {
            float angle = i * Mathf.PI * 2f / count;
            GameObject clone = CreateCloneObject(parent, radius, angle);
            ap.spawnedObjects.Add(clone);
        }

        activePowerUps.Add(ap);
        if (showDebugInfo) Debug.Log($"[PowerUpManager] 生成分身: {count} 个，持续 {duration}s");
    }

    GameObject CreateCloneObject(Transform parent, float radius, float angle)
    {
        GameObject obj = new GameObject("PlayerClone");
        obj.transform.SetParent(parent);
        obj.transform.localPosition = new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0f) * radius;
        obj.transform.localRotation = Quaternion.identity;

        // 外观：尽量与玩家一致，但缩小一些
        SpriteRenderer playerSr = null;
        if (playerController != null)
        {
            playerSr = playerController.GetComponentInChildren<SpriteRenderer>();
        }
        var sr = obj.AddComponent<SpriteRenderer>();
        sr.sortingOrder = 0;
        float scaleFactor = 0.8f; // 分身缩放
        if (playerSr != null && playerSr.sprite != null)
        {
            sr.sprite = playerSr.sprite;
            sr.color = playerSr.color;
            // 缩放相对玩家
            obj.transform.localScale = (playerSr.transform.lossyScale.sqrMagnitude > 0.0001f)
                ? playerSr.transform.localScale * scaleFactor
                : Vector3.one * scaleFactor;
        }
        else
        {
            // 回退：使用简单圆点占位
            sr.color = new Color(0f, 1f, 1f, 0.6f);
            Texture2D tex = new Texture2D(8, 8);
            var pixels = new Color[64];
            for (int i = 0; i < pixels.Length; i++) pixels[i] = Color.white;
            tex.SetPixels(pixels); tex.Apply();
            sr.sprite = Sprite.Create(tex, new Rect(0, 0, 8, 8), new Vector2(0.5f, 0.5f));
            obj.transform.localScale = Vector3.one * scaleFactor;
        }

        // 射击：复制 BulletSpawner 关键参数与资源，实现“同频率、同模式、同子弹”
        if (bulletSpawner != null)
        {
            var bs = obj.AddComponent<BulletSpawner>();
            // 资源与参数
            bs.bulletPrefab = bulletSpawner.bulletPrefab;
            bs.upgradedBulletPrefabs = bulletSpawner.upgradedBulletPrefabs;
            bs.currentBulletLevel = bulletSpawner.currentBulletLevel;
            bs.maxBulletLevel = bulletSpawner.maxBulletLevel;
            bs.fireRate = bulletSpawner.fireRate;
            bs.shootingMode = bulletSpawner.shootingMode;
            bs.bulletSpeed = bulletSpawner.bulletSpeed;
            bs.bulletDamage = bulletSpawner.bulletDamage;
            bs.useObjectPooling = bulletSpawner.useObjectPooling;
            bs.poolSize = bulletSpawner.poolSize;
            bs.autoFire = true;

            // 为分身创建独立发射点，确保从分身位置发射
            GameObject fp = new GameObject("FirePoint");
            fp.transform.SetParent(obj.transform);
            fp.transform.localPosition = Vector3.up * 0.5f;
            bs.firePoint = fp.transform;

            bs.enabled = true;
        }

        return obj;
    }
    
    void ApplyBulletUpgradePowerUp(float duration, float strength)
    {
        if (bulletSpawner == null)
        {
            Debug.LogWarning("[PowerUpManager] bulletSpawner为null，尝试重新查找...");
            InitializeBulletSpawner();
        }

        // 记录并叠加强化
        activePowerUps.Add(new ActivePowerUp(PowerUpController.PowerUpType.BulletUpgradePowerUp, duration, strength));

        // 计算总强度并应用到子弹伤害与速度
        float total = GetTotalEffectStrength(PowerUpController.PowerUpType.BulletUpgradePowerUp);
        int newDamage = Mathf.CeilToInt(originalBulletDamage * total);
        float newSpeed = originalBulletSpeed * total;
        bulletSpawner.bulletDamage = Mathf.Max(1, newDamage);
        bulletSpawner.SetBulletSpeed(newSpeed);
        Debug.Log($"[PowerUpManager] 应用BulletUpgradePowerUp: total={total:F2}, damage={bulletSpawner.bulletDamage}, speed={newSpeed:F2}");
    }
    
    void RemovePowerUpEffect(ActivePowerUp powerUp)
    {
        switch (powerUp.type)
        {
            case PowerUpController.PowerUpType.SpreadShot:
                if (FindActivePowerUp(PowerUpController.PowerUpType.BurstFire) != null)
                {
                    bulletSpawner?.SetShootingMode(BulletSpawner.ShootingMode.Burst);
                }
                else
                {
                    bulletSpawner?.SetShootingMode(originalShootingMode);
                }
                break;
                
            case PowerUpController.PowerUpType.BurstFire:
                if (FindActivePowerUp(PowerUpController.PowerUpType.SpreadShot) != null)
                {
                    bulletSpawner?.SetShootingMode(BulletSpawner.ShootingMode.Spread);
                }
                else
                {
                    bulletSpawner?.SetShootingMode(originalShootingMode);
                }
                break;
            
            case PowerUpController.PowerUpType.UpgradedBullet:
                // 到期时回退一级，最低不低于基础等级
                if (bulletSpawner != null)
                {
                    if (showDebugInfo) Debug.Log("[PowerUpManager] BulletUpgrade到期，回退一级");
                    bulletSpawner.DegradeBulletLevel();
                }
                break;
            
            case PowerUpController.PowerUpType.BulletUpgradePowerUp:
                // 临时将该实例标记为非激活，以正确计算剩余总强度
                powerUp.isActive = false;
                if (bulletSpawner != null)
                {
                    float total = GetTotalEffectStrength(PowerUpController.PowerUpType.BulletUpgradePowerUp);
                    if (total <= 1.001f)
                    {
                        bulletSpawner.bulletDamage = originalBulletDamage;
                        bulletSpawner.SetBulletSpeed(originalBulletSpeed);
                        if (showDebugInfo) Debug.Log("[PowerUpManager] BulletUpgradePowerUp到期，恢复原始伤害与速度");
                    }
                    else
                    {
                        int newDamage = Mathf.CeilToInt(originalBulletDamage * total);
                        float newSpeed = originalBulletSpeed * total;
                        bulletSpawner.bulletDamage = Mathf.Max(1, newDamage);
                        bulletSpawner.SetBulletSpeed(newSpeed);
                        if (showDebugInfo) Debug.Log($"[PowerUpManager] BulletUpgradePowerUp到期，剩余叠加 total={total:F2}，已重新应用");
                    }
                }
                break;

            case PowerUpController.PowerUpType.Clone:
                if (powerUp.spawnedObjects != null)
                {
                    foreach (var obj in powerUp.spawnedObjects)
                    {
                        if (obj != null) Destroy(obj);
                    }
                    powerUp.spawnedObjects.Clear();
                }
                break;
        }
        
        Debug.Log($"移除道具效果: {powerUp.type}");
    }
    
    ActivePowerUp FindActivePowerUp(PowerUpController.PowerUpType type)
    {
        return activePowerUps.Find(p => p.type == type && p.isActive);
    }
    
    float GetTotalEffectStrength(PowerUpController.PowerUpType type)
    {
        float total = 1f;
        foreach (var powerUp in activePowerUps)
        {
            if (powerUp.type == type && powerUp.isActive)
            {
                total += powerUp.effectStrength - 1f;
            }
        }
        return total;
    }
    
}